package api_day12;

import java.util.Random;

public class Consumer extends Thread{
    @Override
    public void run() {
        while (true){
            synchronized (BaoZi.o){
                if (BaoZi.flag){
                    Random random = new Random();
                    int eat = random.nextInt(BaoZi.number) + 1;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("吃了" + eat + "个包子");
                    BaoZi.number -= eat;
                    System.out.println(BaoZi.number);
                    if (BaoZi.number == 0 ) {
                        BaoZi.flag = false;
                        //注意！要先唤醒另一线程，然后再进入另一分支让此线程休眠，否则会死锁
                        BaoZi.o.notify();
                    }
                }else {
                    try {
                        BaoZi.o.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
